<?php

namespace Common\Service;

class GenerateCodeService {

  var $filepath = array(
    'model'      => 'Apps/Common/Model/',
    'service'    => 'Apps/Common/Service/',
    'controller' => 'Apps/{module}/Controller/',
    'js'         => 'Public/js/{module}/' ,
    'view'       => 'Apps/{module}/View/{controller_name}/index.html',
  );
  
  var $tempfile = array(
    'model'      => 'Apps/Common/Temp/model.txt',
    'service'    => 'Apps/Common/Temp/service.txt',
    'controller' => 'Apps/Common/Temp/controller.txt',
    'js'         => array(
      'div'   => 'Apps/Common/Temp/js.txt',
      'modal' => 'Apps/Common/Temp/js_modal.txt',
    ),
    'view'       => array(
      'div'   => 'Apps/Common/Temp/view.txt',
      'modal' => 'Apps/Common/Temp/view_modal.txt',
    ),
  );
  
  private static $instance;

  public static function instance() {
    if (self::$instance == null) {
      $instance = new GenerateCodeService();
    }
    return $instance;
  }
  
  function get_by_tablename($tablename) {
    $sql = "SELECT COLUMN_NAME AS field_name, DATA_TYPE AS field_type,  COLUMN_DEFAULT AS field_default , COLUMN_COMMENT AS field_comment
            FROM INFORMATION_SCHEMA.COLUMNS
            WHERE table_name = '$tablename'
            AND table_schema = '" . C('DB_NAME') . "'";

    $M = M();
    $data = $M->query($sql);
    return $data;
  }

  function get_model_info($tablename) {
    $name = $this->get_model_name_by_tablename($tablename);

    $filepath = $this->filepath['model'];

    return array(
      'filename' => $filepath . $name . 'Model.class.php',
      'classname' => $name . 'Model',
      'name' => $name,
      'tablename' => strtolower($tablename),
    );
  }

  function get_model_name_by_tablename($tablename) {
    $tmp = explode('_', $tablename);

    $name = '';
    foreach ($tmp as $s) {
      $name .= ucfirst($s);
    }

    return $name;
  }

  /**
   * 生成Model
   * @param array $data
   * @return type
   */
  function add_model($data) {
    $content = file_get_contents($this->tempfile['model']);

    foreach ($data as $key => $val) {
      $content = str_replace('{' . $key . '}', $val, $content);
    }

    $filename = $data['filename'];
    if (file_exists($filename)) {
      return ajax_arr('生成失败，文件已存在');
    }

    file_put_contents($filename, $content);
    return ajax_arr($data['classname'] . '生成成功', TRUE);
  }

  /**
   * 获取 service 信息
   * @param type $tablename
   * @return type
   */
  function get_service_info($tablename) {
    $modelname = $this->get_model_name_by_tablename($tablename);

    $name = $modelname;
    $filepath = $this->filepath['service'];
    return array(
      'modelname' => $modelname,
      'filename' => $filepath . $name . 'Service.class.php',
      'classname' => $name . 'Service',
      'name' => $name,
    );
  }

  /**
   * 生成service文件
   * @param type $data
   * @return type
   */
  function add_service($data) {
    $content = file_get_contents($this->tempfile['service']);
      
    $defaultrow_data = $data['defaultrow'];
    unset($data['defaultrow']);
    
    $data['defaultrow'] = '';
    foreach ( $defaultrow_data as $row ) {
      $field = "'" . $row['field_name'] . "'";
      $value = $row['field_default'] == 'CURRENT_TIMESTAMP' ?  " date('Y-m-d H:i:s') , " : "'" . $row['field_default'] . "' , " ;
      $data['defaultrow'] .= "$field => $value \r\n";
    }
    
    foreach ($data as $key => $val) {
      $content = str_replace('{' . $key . '}', $val, $content);
    }

    $filename = $data['filename'];
    if (file_exists($filename)) {
      return ajax_arr('生成失败，文件已存在');
    }

    //echo $filename ;
    file_put_contents($filename, $content);
    return ajax_arr($data['classname'] . '生成成功', TRUE);
  }

  /**
   * 取controller信息
   * @param type $module
   * @param type $servicename
   * @return type
   */
  function get_controller_info( $module , $tablename ) {
    $filepath = str_replace('{module}', "{$module}", $this->filepath['controller']);
    
    $modelname = $this->get_model_name_by_tablename($tablename);
    $service =  $modelname ;
    
    return array(
      'filename' => $filepath . $service . 'Controller.class.php',
      'service' => $service ,
      'service_classname' => $service. 'Service' ,
      'module' => $module ,
      'module_classname' => $module . 'Controller',
      'name' => strtolower( $service ) ,
      'classname' => $service . 'Controller',
    );
  }
  
  /**
   * 
   * @param type $data
   * @return type
   */
  function add_controller( $data ) {
    $content = file_get_contents($this->tempfile['controller']);

    foreach ($data as $key => $val) {
      $content = str_replace('{' . $key . '}', $val, $content);
    }

    $filename = $data['filename'];
    if (file_exists($filename)) {
      return ajax_arr('生成失败，文件已存在');
    }

    file_put_contents($filename, $content);
    return ajax_arr($data['classname'] . '生成成功', TRUE);
  }
  
  function get_js_info( $module , $tablename ) {
    $low_module = strtolower($module);
    
    $filepath = str_replace('{module}', "{$low_module}", $this->filepath['js']);
    
    $modelname = $this->get_model_name_by_tablename($tablename);
    
    $classname = $modelname ;
    $name = $tablename ;
    
    return array(
      'filename' => $filepath . $name  . '.js',
      'classname' => $classname ,
    );
  }
  
  function add_js( $data ) {
    $content = file_get_contents($this->tempfile['js'][$data['type']]);

    unset($data['type']);
    
    foreach ($data as $key => $val) {
      $content = str_replace('{' . $key . '}', $val, $content);
    }

    $filename = $data['filename'];
    if (file_exists($filename)) {
      return ajax_arr('生成失败，文件已存在');
    }

    file_put_contents($filename, $content);
    return ajax_arr($data['classname'] . '生成成功', TRUE);
  }
  
  function get_view_info( $module , $tablename ) {
    $modelname = $this->get_model_name_by_tablename($tablename);
    $controller_name =  $modelname;
    $name = strtolower( $modelname );
    
    $filename = str_replace('{module}', "{$module}", $this->filepath['view']);
    $filename = str_replace('{controller_name}', "{$controller_name}", $filename );
    
    $filepath = 'Apps/' . $module . '/View/' . $controller_name ;
    if ( !file_exists($filepath) ) {
      mkdir($filepath, 0777);
    }
    
    return array(
      'filename'     => $filename ,
      'low_module'   => strtolower($module),
      'js_filename'  => $tablename ,
      'js_classname' => $controller_name ,
    );
  }
  
  function add_view( $data ) {
    $select_row = $data['select_row'];
    unset($data['select_row']);
    
    $data['grid'] = '' ; //grid
    $data['form'] = '' ; //form
    foreach ( $select_row as $row ) {
      $field = $row['field_name'] ;
      $text  = $row['field_text'] ;
      $sort = $row['field_sort'] == 0 ? '' : 'data-sortable="true"';
      $format = empty( $row['field_format'] ) ? '' : 'data-formatter="'. $row['field_format'] .'"';
      $data['grid'] .= '<th width="'.$row['field_width'] .'" data-field="'. $field .'" '. $sort .' '. $format .'>'. $text .'</th>' . " \r\n";
      $data['form'] .= '<div class="form-group">
              <label class="col-sm-3 control-label">'. $text .'</label>
              <div class="col-sm-7">
                <input name="'. $field .'" placeholder="'. $text .'" data-valid="required" data-tips="请填写正确的'. $text .'" type="text" class="form-control" >
              </div>
            </div>'. " \r\n";
    }
    
    
    $content = file_get_contents($this->tempfile['view'][$data['type']]);
    unset($data['type']);
    
    foreach ($data as $key => $val) {
      $content = str_replace('{' . $key . '}', $val, $content);
    }

    $filename = $data['filename'];
    if (file_exists($filename)) {
      return ajax_arr('生成失败，文件已存在');
    }

    file_put_contents($filename, $content);
    return ajax_arr($data['filename'] . '生成成功', TRUE);
  }
}
